package com.hup.vd.view.taskEditor;

import com.alibaba.fastjson.JSON;
import com.hup.utils.commons.exception.AppCommonException;
import com.hup.utils.commons.start.DialogHelper;
import com.hup.utils.commons.start.LookThemeUtil;
import com.hup.utils.commons.start.SpringContext;
import com.hup.utils.swing.customView.BaseUndoText;
import com.hup.utils.swing.frame.BaseDialog;
import com.hup.utils.swing.frame.SingletonWindowHelper;
import com.hup.vd.model.config.TaskInfo;
import com.hup.vd.service.TaskService;
import com.hup.vd.view.MainFrame;
import lombok.extern.slf4j.Slf4j;

import javax.swing.JFrame;
import javax.swing.undo.UndoManager;
import java.util.Objects;

/**
 * 编辑任务弹窗
 *
 * @author hugan
 * @date 2025/10/9
 */
@Slf4j
public class TaskEditorDialog extends BaseDialog {

    private final TaskInfo task;
    private TaskEditorForm form;
    private String initTask;

    public static void doShow(TaskInfo task) {
        if (task.isRunning()) {
            throw new AppCommonException("请先停止任务");
        }
        TaskEditorDialog dialog = new TaskEditorDialog(task);
        dialog.setVisible(true);
        dialog.toFront();
    }

    public TaskEditorDialog(TaskInfo task) {
        super("编辑任务");//会阻塞主窗口
        this.task = task;

        initView(task);
        initListener();
    }

    private void initView(TaskInfo task) {
        form = new TaskEditorForm();
        setContentPane(form.root);

        LookThemeUtil.initFrameSize(this, 800, 600);
        JFrame parent = SingletonWindowHelper.getWindow(MainFrame.class);
        setLocationRelativeTo(parent);
        setAlwaysOnTop(parent.isAlwaysOnTop());
        BaseUndoText.initUndo(form.txtData, new UndoManager());

        setSubTitle(task.getUid());
        initTask = JSON.toJSONString(task, true);
        form.txtData.setText(initTask);
    }

    private void initListener() {
        form.btnOk.addActionListener(e -> doInBackground("保存", this::onOK));
        form.btnCancel.addActionListener(e -> onCancel());
    }

    private void onOK() {
        boolean changed = !Objects.equals(form.txtData.getText(), initTask);
        if (!changed) {
            dispose();
            return;
        }

        TaskInfo edited = JSON.parseObject(form.txtData.getText(), TaskInfo.class);
        SpringContext.getBean(TaskService.class).reloadTaskFormEdit(task, edited);
        dispose();
    }

    @Override
    public void onCancel() {
        boolean changed = !Objects.equals(form.txtData.getText(), initTask);
        if (!changed) {
            dispose();
            return;
        }
        DialogHelper.yesNo("未保存,确定退出?").okAction(this::dispose).show(this);
    }

}
